const app = getApp();
const util = require('../../utils/time.js')
const db = wx.cloud.database()
const _ = db.conmmand
Page({

    data: {
        location: null, // 位置
        index: null,
        picker: ['便民利民', '扶贫帮困', '就业指导', '治安维稳', '卫生保健', '环境维护', '宣传教育', '文体娱乐', '助农增收', '心理咨询'],
        pickerDegree: 0, // 紧急程度选择 1 紧急 2 尽快 3 正常
        imgList: [],
        textareaAValue: '', // 内容
        clientHeight: 557, // scroll-view 高度
        scrollTop: 0, // 距离顶部高度,
        dateStart: '2018-12-25',
        dateEnd: '2019-12-25',
        time: '12:00',
        title: '', // 标题
        sumPeople: 0, // 总人数
        hour: 1,
        addIcon: 'cloud://cloud1-3gwgwntc19418eac.636c-cloud1-3gwgwntc19418eac-1312065174/images/icon/add.png',
        subIcon: 'cloud://cloud1-3gwgwntc19418eac.636c-cloud1-3gwgwntc19418eac-1312065174/images/icon/sub.png'
    },
    // scroll-view 
    onLoad(options) {
        let that = this;
        // 动态获取scroll-view 高度
        wx.getSystemInfo({
            success: function (res) {
                let screenHeight = wx.getSystemInfoSync().windowHeight
                // console.log(screenHeight)
                let query = wx.createSelectorQuery().in(that);
                query.select('.footer_button').boundingClientRect();
                query.select('.head').boundingClientRect();
                query.exec(res => {
                    // console.log(res)
                    let h = res[0].height;
                    let h1 = res[1].height;
                    console.log(screenHeight - h - h1)
                    that.setData({
                        clientHeight: screenHeight - h - h1
                    })
                })
            }
        })
        // 获取当前时间
        var time = util.formatTime(new Date()) // 获取时间
        // console.log(time.split(' ')[0].replaceAll('/','-'))
        time = time.split(' ')[0].replaceAll('/', '-')
        let year = parseInt(time.slice(0, 4))
        year = year + 1
        // console.log(year + time.slice(4,10))
        this.setData({
            dateStart: time.split(' ')[0].replaceAll('/', '-'), // 2022-06-27 格式
            dateEnd: year + time.slice(4, 10)
        })
    },
    addHour() {
        if (this.data.hour < 8) {
            this.setData({
                hour: this.data.hour + 1
            })
        }
    },
    subHour() {
        if (this.data.hour > 1) {
            this.setData({
                hour: this.data.hour - 1
            })
        }
    },
    // 招募人数
    peopleInput(e) {
        this.setData({
            sumPeople: e.detail.value
        })
    },
    // 选择时间
    DateChange(e) {
        console.log(e.detail.value)
        this.setData({
            dateStart: e.detail.value
        })
    },
    // 上报
    save() {
        var app = getApp()
        
        if (this.data.textareaAValue != '' && this.data.imgList.length != 0 
        && this.data.picker[this.data.index] != undefined && this.data.pickerDegree != 0 
        && this.data.location != null && this.data.sumPeople != 0) {
            db.collection('activity').add({
                data: {
                    "content": this.data.textareaAValue,
                    "url": this.data.imgList, 
                    "title": this.data.title,
                    "index": this.data.picker[this.data.index],
                    "degree": this.data.pickerDegree,
                    "location": this.data.location,
                    "time": this.data.time,
                    "date": this.data.dateStart,
                    "hour": this.data.hour,
                    "sumPeople": this.data.sumPeople,
                    "currentPeople": 0,
                    "name": app.globalData.userinfo.name, // 发布人
                    "status": "未开始" , // 活动状态 未开始 进行中 已完结
                    "day": 0, // 距离还有多少天
                    "distance": 0, // 距离
                    "faceImg": app.globalData.userinfo.faceImg ,// 发布人头像
                    "userList": []
                },
                success: function (res) {
                    // res 是一个对象，其中有 _id 字段标记刚创建的记录的 id
                    console.log(res)
                    wx.showToast({
                        title: '上传成功',
                        icon: 'success'
                    })
                    setTimeout(() => {
                        wx.navigateBack({
                            delta: 1
                        })
                    }, 1000);
                }
            })

            const _ = db.command
              // 发布活动次数加一
              db.collection('user').where({_id: app.globalData.userinfo._id}).update({
                data: {
                  serviceNum: _.inc(1)
                }
              }).then(res => {
                // res.data 包含该记录的数据
                console.log(res)
              })
        } else {
            if(this.data.textareaAValue == '') {
                wx.showToast({
                    title: '事件内容未填写',
                    icon: 'error'
                })
            } else if (this.data.imgList.length == 0) {
                wx.showToast({
                    title: '未上传图片',
                    icon: 'error'
                })
            } else if (this.data.picker[this.data.index] == undefined) {
                wx.showToast({
                    title: '未选择支援类型',
                    icon: 'error'
                })
            } else if(this.data.pickerDegree == 0) {
                wx.showToast({
                    title: '未选择紧急程度',
                    icon: 'error'
                })
            } else if(this.data.location == null) {
                wx.showToast({
                    title: '为选择地址',
                    icon: 'error'
                })
            } else if (this.data.sumPeople == 0) {
                wx.showToast({
                    title: '招募总人数不能为空',
                    icon: 'error'
                })
            }
            
        }
    },
    // 紧急程度
    choose(e) {
        // console.log('选中',e.currentTarget.dataset.index)
        this.setData({
            pickerDegree: e.currentTarget.dataset.index
        })
    },
    // 取消按钮
    cancel() {
        wx.navigateBack({
            delta: 1,
        })
    },
    submitNotWan: function () {
        this.setData({
            show: false,
            scrollTop: 617
        })
    },
    TimeChange(e) {
        this.setData({
            time: e.detail.value
        })
    },
    submitWan: function () {
        this.setData({
            show: true,
            scrollTop: 1000
        })
    },
    onClickLeft() {
        wx.showToast({
            title: '点击返回',
            icon: 'none'
        });
        wx.navigateBack({
            delta: 1,
        })
    },
    PickerChange(e) {
        console.log(e);
        this.setData({
            index: e.detail.value
        })
    },
    MultiChange(e) {
        this.setData({
            multiIndex: e.detail.value
        })
    },
    // 选择位置
    onChooseLocation() {
        wx.chooseLocation({
            success: (res) => {
                console.log(res)
                this.setData({
                    location: res
                })
            }
        });
    },
    ChooseImage() {
        wx.chooseImage({
            count: 4, //默认9
            sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
            sourceType: ['album', 'camera'], //从相册选择
            success: (res) => {
                wx.showLoading({
                    title: '图片上传中...',
                })
                var time = util.formatTime(new Date()) // 获取时间
                var FilePaths = []
                const temFilePaths = res.tempFilePaths
                let promiseArr = []
                for (let i = 0; i < temFilePaths.length; i++) {
                    let promise = new Promise((resolve, reject) => {
                        var randstring = Math.floor(Math.random() * 1000000).toString() + '.png'
                        randstring = time + '-' + randstring
                        wx.cloud.uploadFile({
                            cloudPath: 'orderimg/' + randstring,
                            filePath: temFilePaths[i],
                            success: res => {
                                // get resource ID
                                console.log(res.fileID)
                                FilePaths[i] = res.fileID
                                resolve(res)
                            },
                            fail: err => {
                                reject(error);
                            }
                        })
                    })
                    promiseArr.push(promise)
                }
                Promise.all(promiseArr).then((result) => {
                    console.log('上传图片1', FilePaths)
                    if (this.data.imgList.length != 0) {
                        this.setData({
                            imgList: this.data.imgList.concat(FilePaths)
                        })
                    } else {
                        this.setData({
                            imgList: FilePaths
                        })
                    }
                    wx.hideLoading()
                })
            }
        });
    },
    ViewImage(e) {
        wx.previewImage({
            urls: this.data.imgList,
            current: e.currentTarget.dataset.url
        });
    },
    DelImg(event) {
        console.log(event.currentTarget.dataset.index)
        var id = event.currentTarget.dataset.index
        var imgList = this.data.imgList
        wx.cloud.deleteFile({
            fileList: [imgList[id]]
        }).then(res => {
            imgList.splice(id, 1)
            this.setData({
                imgList: imgList
            })
            console.log(res.fileList)
        }).catch(error => {})
    },
    textareaAInput(e) {
        this.setData({
            textareaAValue: e.detail.value
        })
    },
    titleInput(e) {
        this.setData({
            title: e.detail.value
        })
    }

})